<template>
  <van-popup
    v-model:show="showScoreRangePopup"
    position="center"
    round
    :style="{ overflow: 'hidden' }"
    closeable
    @close="beforeClose"
  >
    <div class="score-range-popup">
      <div class="title">一分一段表</div>
      <div class="table" ref="tableContainer">
        <MyTable
          :data="tableData"
          :columns="columns"
          maxHeight="370px"
          @scroll="handleScroll"
        >
          <template #score="{ row }">
            <span v-if="row.minScore !== row.maxScore">
              {{ row.minScore }} - {{ row.maxScore }}
            </span>
            <span v-else>{{ row.minScore }}</span>
          </template>
        </MyTable>
        <div v-if="loading" class="loading">
          <van-loading size="16px">加载中...</van-loading>
        </div>
        <div v-if="!hasMore && tableData.length > 0" class="no-more">
          没有更多数据了
        </div>
      </div>
    </div>
  </van-popup>
</template>
<script setup>
import { ref, onMounted, computed, nextTick, watch } from 'vue';
import { useVolunteerStore } from '@/store/volunteer';
import MyTable from '@/components/MyTable.vue';
import { scoreList } from '@/api/volunteer';

const store = useVolunteerStore();
const volunteerInfo = computed(() => store.volunteerInfo);

const showScoreRangePopup = ref(true);
const tableContainer = ref(null);

const emit = defineEmits(['close']);

const columns = ref([
  {
    label: '分数',
    prop: 'score',
    width: '30%',
  },
  {
    label: '本段人数',
    prop: 'segmentNum',
    width: '30%',
  },
  {
    label: '累计人数',
    prop: 'totalNum',
    width: '40%',
  },
]);

const tableData = ref([]);
const pageNo = ref(1);
const pageSize = ref(15);
const loading = ref(false);
const hasMore = ref(true);
const scrollTimer = ref(null);

const beforeClose = () => {
  emit('close');
};

// 重置数据状态
const resetData = () => {
  tableData.value = [];
  pageNo.value = 1;
  hasMore.value = true;
  loading.value = false;
};

const scoreListFn = async (isLoadMore = false) => {
  if (loading.value || (!isLoadMore && !hasMore.value)) return;

  loading.value = true;

  try {
    const params = {
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      localRegionId: volunteerInfo.value.regionId,
      subjectType: volunteerInfo.value.subjectType,
      recordYear: volunteerInfo.value.searchRankYear,
    };

    const res = await scoreList(params);

    if (res.code === 200) {
      if (isLoadMore) {
        // 加载更多时，追加数据
        tableData.value = [...tableData.value, ...res.data];
      } else {
        // 首次加载时，替换数据
        tableData.value = res.data;
      }

      // 判断是否还有更多数据
      hasMore.value = tableData.value.length < res.pageparam.sums;

      if (hasMore.value) {
        pageNo.value++;
      }
    }
  } catch (error) {
    console.error('获取分数列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 防抖处理滚动事件
const handleScroll = (event) => {
  if (scrollTimer.value) {
    clearTimeout(scrollTimer.value);
  }

  scrollTimer.value = setTimeout(() => {
    const { scrollTop, scrollHeight, clientHeight } = event.target;

    // 当滚动到距离底部50px时触发加载更多
    if (
      scrollHeight - scrollTop - clientHeight < 80 &&
      !loading.value &&
      hasMore.value
    ) {
      scoreListFn(true);
    }
  }, 100);
};

// 监听弹窗显示状态，当重新打开时重置数据
watch(showScoreRangePopup, (newVal) => {
  if (newVal) {
    resetData();
    nextTick(() => {
      scoreListFn();
    });
  }
});

onMounted(() => {
  resetData();
  scoreListFn();
});
</script>

<style scoped lang="scss">
.score-range-popup {
  width: 640px;
  padding: 32px 32px 0px 32px;
  .title {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    text-align: center;
    margin-bottom: 18px;
  }
  .table-header {
    display: flex;
    height: 54px;
    line-height: 54px;
    justify-content: flex-start;
    color: #333;
    background: #f0f2f6;
    font-weight: bold;
    font-size: 26px;
    //上圆角
    border-top-left-radius: 16px;
    border-top-right-radius: 16px;
    .table-header-item {
      padding: 10px 12px;
      text-align: left;
    }
    .table-header-item:first-child {
      width: 30%;
    }
    .table-header-item:nth-child(2) {
      width: 30%;
    }
    .table-header-item:last-child {
      width: 40%;
    }
  }
  .table {
    height: 45vh;
    overflow-y: scroll;
    position: relative;
    :deep(.my-table) {
      th {
        font-weight: normal;
        padding: 6px 24px;
        font-size: 22px;
        border: none;
        color: #777770;
        background: #f0f2f6;
      }
      td {
        padding: 16px 24px;
        font-size: 24px;
        border: none;
        color: #333;
        background: #f7f9fb;
      }
    }
  }
  .loading {
    text-align: center;
    padding: 20px 0;
    color: #999;
    font-size: 20px;
  }
  .no-more {
    text-align: center;
    padding: 20px 0;
    color: #999;
    font-size: 20px;
  }
}
</style>
